package com.example.fengyungo_user.activity.me;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.example.fengyungo_user.R;
import com.example.fengyungo_user.activity.BaseActivity;
import com.example.fengyungo_user.constant.ResultConstant;
import com.example.fengyungo_user.constant.UserConstant;
import com.example.fengyungo_user.domain.User;
import com.example.fengyungo_user.utils.OkHttpUtils;
import com.example.fengyungo_user.utils.ThreadPoolUtil;
import com.example.fengyungo_user.utils.UserUtils;

import org.json.JSONObject;

/**
 * 编辑个人资料
 *
 * @author XLR
 */
public class EditMyInfoActivity extends BaseActivity implements View.OnClickListener {

    private static final String TAG = "EditMyInfoActivity";

    /**
     * 提示修改什么属性
     */
    TextView title;
    /**
     * 确定按钮
     */
    Button ok;
    /**
     * 返回
     */
    ImageButton back;
    /**
     * 要修改的属性
     */
    int editAttribute;
    /**
     * 属性
     */
    String[] attributes = {"修改昵称", "修改电话号码", "修改性别", "修改账号", "修改邮箱", "修改头像"};
    /**
     * 用户信息
     */
    User user;
    /**
     * 输入框
     */
    EditText editText;
    /**
     * 进度条
     */
    ProgressBar progressBar;
    /**
     * SharedPreferences.Editor editor = getSharedPreferences("data", MODE_PRIVATE).edit();
     */
    SharedPreferences.Editor editor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_my_info);

        editText = findViewById(R.id.edit);
        progressBar = findViewById(R.id.progress_bar);

        editor = getSharedPreferences(UserConstant.SP_NAME, MODE_PRIVATE).edit();

        // 获取要修改的属性
        Intent intent = getIntent();
        editAttribute = intent.getIntExtra(UserConstant.EDIT_ATTRIBUTE, 1);

        // 获取用户信息
        user = UserUtils.getUserInfo(this);
        Log.d(TAG, "onCreate: driver:" + user);
        // 初始化输入框
        initEditText(editAttribute);

        back = findViewById(R.id.back);
        back.setOnClickListener(this);

        title = findViewById(R.id.title);
        title.setText(attributes[editAttribute]);

        ok = findViewById(R.id.ok);
        ok.setOnClickListener(this);
    }

    /**
     * 点击事件
     *
     * @param view View
     */
    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.back) {
            finish();
        } else if (id == R.id.ok) {
            edit();
        }
    }

    /**
     * 修改个人资料的具体操作
     */
    private void edit() {
        // 修改昵称
        if (editAttribute == UserConstant.EDIT_NICKNAME) {
            updateNickname();
        }
        // 修改性别
        else if (editAttribute == UserConstant.EDIT_SEX) {
            updateSex();
        }
        // 修改电话号码
        else if (editAttribute == UserConstant.EDIT_PHONE) {
            updatePhone();
        }
    }

    /**
     * 先初始化输入框中的为原
     */
    private void initEditText(int editAttribute) {
        Log.d(TAG, "initEditText: editAttribute:"+editAttribute);
        // 昵称
        if (editAttribute == UserConstant.EDIT_NICKNAME) {
            editText.setText(user.getUserNickname());
        }
        // 性别
        else if (editAttribute == UserConstant.EDIT_SEX) {
            editText.setText(user.getUserSex());
        }
        // 电话号码
        else if (editAttribute == UserConstant.EDIT_PHONE) {
            editText.setText(user.getUserPhone());
        }
    }

    /**
     * 修改昵称
     */
    private void updateNickname() {
        updateAttribute("updateNicknameById",UserConstant.NICKNAME);
    }

    /**
     * 修改性别
     */
    private void updateSex() {
        updateAttribute("updateSexById",UserConstant.SEX);
    }

    /**
     * 修改电话号码
     */
    private void updatePhone() {
        updateAttribute("updatePhoneById",UserConstant.PHONE);
    }

    /**
     * 对某一信息进行修改
     * @param putMapping put请求的接口前缀
     * @param spKey SharedPreferences中的key
     */
    private void updateAttribute(String putMapping,String spKey) {
        String input = editText.getText().toString();
        progressBar.setVisibility(View.VISIBLE);
        // 先修改数据库，若成功再将SharedPreferences中储存的修改
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                String url = UserConstant.URL_USER_USER + "/" + putMapping + "/" + user.getUserId() + "/" + input;
                try {
                    String responseData = OkHttpUtils.put(url, "");
                    JSONObject jsonObject = new JSONObject(responseData);
                    int code = jsonObject.getInt(ResultConstant.CODE);
                    String msg = jsonObject.getString(ResultConstant.MSG);
                    // 修改成功
                    if (code == 1) {
                        // 修改SharedPreferences中的nickname
                        editor.putString(spKey, input);
                        editor.apply();
                        // 提示
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                progressBar.setVisibility(View.GONE);
                                Toast.makeText(EditMyInfoActivity.this, getString(R.string.update_success), Toast.LENGTH_SHORT).show();
                                finish();
                                // todo 返回到上一个fragment时需要自动刷新
                            }
                        });
                    }
                    // 修改失败
                    else {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                progressBar.setVisibility(View.GONE);
                                Toast.makeText(EditMyInfoActivity.this, msg, Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                } catch (Exception e) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            progressBar.setVisibility(View.GONE);
                            Toast.makeText(EditMyInfoActivity.this, getString(R.string.connection_error), Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        };
        ThreadPoolUtil.execute(runnable);
    }
}